import { deleteGoods, getParseGoodsList } from '@/services/goods';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import { PageContainer, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, message, Popconfirm, Space, Tag, Image } from 'antd';
import React, { useRef, useState } from 'react';
import type { GoodsItemType, GoodsSkuType } from './type';
import UpdateForm from './components/UpdateForm';
import { goodsStateOptions, saleTypeOptions } from '@/const';

interface ColorMap {
  [any: string]: string;
}

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: GoodsItemType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = selectedRows.map((row) => row.id);
    await deleteGoods(ids);
    hide();
    message.success('删除成功！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败！');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const [mode, setMode] = useState<string>('add');

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<GoodsItemType>();

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns[] = [
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '商品sku',
      dataIndex: 'skuCode',
      render: (data, row) => {
        const { mallGoodsSkus } = row;
        return (
          <Space size={[0, 8]} wrap>
            {mallGoodsSkus && mallGoodsSkus.length
              ? mallGoodsSkus.map((item: GoodsSkuType) => {
                  return (
                    <Tag key={item.id}>
                      {item.skuCode} / {item.specs}
                    </Tag>
                  );
                })
              : '-'}
          </Space>
        );
      },
    },
    {
      title: '商品类型',
      dataIndex: 'categoryName',
      search: false,
      width: '80px',
    },
    {
      title: '商品描述',
      dataIndex: 'description',
      search: false,
    },
    {
      title: '商品上架状态',
      dataIndex: 'isOnSale',
      search: false,
      render: (data: any) => {
        const item = saleTypeOptions.find((item) => item.value === data);
        const colorMap: ColorMap = {
          '1': 'green',
          '2': 'warning',
          '3': 'default',
        };
        const key: string = data || '3';
        return item ? <Tag color={colorMap[key]}>{item?.label}</Tag> : '-';
      },
    },
    {
      title: '商品可售状态',
      dataIndex: 'goodsState',
      search: false,
      render: (data: any) => {
        const item = goodsStateOptions.find((item) => item.value === data);
        const colorMap: ColorMap = {
          '1': 'green',
          '2': 'warning',
          '3': 'blue',
        };
        const key: string = data || '3';
        return item ? <Tag color={colorMap[key]}>{item?.label}</Tag> : '-';
      },
    },
    {
      title: '商品主图',
      dataIndex: 'mainPic',
      search: false,
      render: (data: any) => {
        return (
          <Image
            width={100}
            height={100}
            src={data}
          />
        )
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '160px',
      render: (_, record) => [
        <Button
          onClick={() => {
            handleUpdateModalOpen(true);
            setMode('edit');
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="提醒"
          description="请确认是否删除该记录?"
          onConfirm={() => {
            handleRemove([record]).then((res) => {
              res && actionRef.current && actionRef.current.reload();
            });
          }}
        >
          <Button danger>删除</Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<GoodsItemType, COMTYPE.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleUpdateModalOpen(true);
              setMode('add');
              setCurrentRow(undefined);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={getParseGoodsList}
        columns={columns}
        rowSelection={{
          onChange: (_) => {
          },
        }}
      />
      <UpdateForm
        onSubmit={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        mode={mode}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<GoodsItemType>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<GoodsItemType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
